<style lang="scss">
@import "../uv.scss";
</style>
<template>
  <div class="launch">
    <div class="" style="height: calc(100vh - 44px);overflow: hidden;display: flex;justify-content: space-between;flex-direction: column;">
      <div class="h100 p1757638117 oy" style="transition: 0.3s;" :style="{transform: `translateY(${translateY}px)`}">
        <uv-form labelWidth="160rpx" :labelStyle="{fontSize: '30rpx', fontWeight: 500}" labelPosition="left" :model="launchForm" :rules="rules" ref="form">
          <div class="bfff images pl30 pr30 mt20" style="text-align: right;">
            <uv-form-item label="商品图片" prop="images" labelPosition="top">
              <uv-upload @delete="deletePic" @afterRead="afterRead" :fileList="launchForm.images" name="images" :maxCount="6">
                <div class="p1757567255 f mt20 aic jcc">
                  <uv-icon size="100rpx" color="#C9CACA" name="camera"></uv-icon>
                </div>
              </uv-upload>
            </uv-form-item>
          </div>
          <div class="bfff video_link pl30 pr30 mt20" style="text-align: right;">
            <uv-form-item label="商品视频" prop="video_link" labelPosition="top">
              <uv-upload @delete="deletePic" @afterRead="afterRead" accept="video" :fileList="launchForm.video_link" name="video_link" :maxCount="1">
                <div class="p1757567255 f aic jcc mt20">
                  <uv-icon size="100rpx" color="#C9CACA" name="camera"></uv-icon>
                </div>
              </uv-upload>
            </uv-form-item>
          </div>
          <div class="bfff pl30 pr30 mt20" style="text-align: right;">
            <uv-form-item label="产品名称" prop="store_name" borderBottom>
              <uv-input inputAlign="right" v-model="launchForm.store_name" disabledColor="#ffffff" placeholder="请输入产品名称" border="none" placeholderStyle="color:#C9CACA;font-size:30rpx"></uv-input>
            </uv-form-item>
            <uv-form-item label="描述信息" prop="store_info" borderBottom>
              <uv-input inputAlign="right" v-model="launchForm.store_info" disabledColor="#ffffff" placeholder="请输入描述信息" border="none" placeholderStyle="color:#C9CACA;font-size:30rpx"></uv-input>
            </uv-form-item>
            <uv-form-item label="产品保障" borderBottom>
              <div style="text-align: right;" class="fz30 fw500 w100">付款后3天内发货·七天无理由退货</div>
            </uv-form-item>
            <uv-form-item label="是否免邮" prop="is_postage" :borderBottom="launchForm.is_postage == 0 ? true : false">
              <div class="f w100" style="justify-content: flex-end;">
                <uv-switch activeValue="1" inactiveValue="0" activeColor="#22AC38" v-model="launchForm.is_postage"></uv-switch>
              </div>
            </uv-form-item>
            <div class="pt5 pb5" id="launchForm-postage">
              <uv-form-item v-if="launchForm.is_postage == 0" label="邮费" prop="postage" @click="dotDisabled = false,openKeyboardTap('postage')">
                <div :class="!launchForm.postage && 'cD8D8D8'" class="p1757903903 number-container">{{ launchForm.postage || '请输入邮费' }}<div class="cursor-blink" v-if="currentId ==  `launchForm-postage`">|</div>
                </div>
              </uv-form-item>
            </div>
          </div>
          <div class="bfff pl30 pr30 mt20" style="text-align: right;">
            <uv-form-item label="产品分类" prop="_cate_id" borderBottom @click="openTap('_cate_id')">
              <div :class="!launchForm._cate_id && 'cD8D8D8'" class="p1757903903 number-container">{{ launchForm._cate_id || '请选择产品分类' }}</div>
              <template v-slot:right>
                <uv-icon name="arrow-right"></uv-icon>
              </template>
            </uv-form-item>
            <uv-form-item label="产品规格" prop="_sku_object" :borderBottom="!launchForm._sku_object ? true : false">
              <div class="w100 fac">
                <div @click="navigateToTap" :class="!launchForm._sku_object && 'cC9CACA'" class="p1757903903 dib number-container">{{ launchForm._sku_object || '' }}</div>
                <div v-if="launchForm._sku_object" @click="launchForm._sku_object = ''" class="pr10 dib pl10">
                  <uv-icon name="close-circle"></uv-icon>
                </div>
              </div>
              <template v-slot:right>
                <uv-icon @click="navigateToTap" name="arrow-right"></uv-icon>
              </template>
            </uv-form-item>
            <div class="pt5 pb5" id="launchForm-price">
              <uv-form-item v-if="!launchForm._sku_object" label="售价" borderBottom prop="price" @click="dotDisabled = false,openKeyboardTap('price')">
                <div :class="!launchForm.price && 'cD8D8D8'" class="p1757903903 number-container">{{ launchForm.price || '¥' }}<div class="cursor-blink" v-if="currentId ==  `launchForm-price`">|</div>
                </div>
              </uv-form-item>
            </div>
            <div class="pt5 pb5" id="launchForm-market_price">
              <uv-form-item v-if="!launchForm._sku_object" label="划线价" borderBottom prop="market_price" @click="dotDisabled = false,openKeyboardTap('market_price')">
                <div :class="!launchForm.market_price && 'cD8D8D8'" class="p1757903903 number-container">{{ launchForm.market_price || '¥' }}<div class="cursor-blink" v-if="currentId ==  `launchForm-market_price`">|</div>
                </div>
              </uv-form-item>
            </div>

            <div class="pt5 pb5" id="launchForm-stock">
              <uv-form-item v-if="!launchForm._sku_object" label="库存" prop="stock" @click="dotDisabled = false,openKeyboardTap('stock')">
                <div :class="!launchForm.stock && 'cD8D8D8'" class="p1757903903 number-container">{{ launchForm.stock || '请输入' }}<div class="cursor-blink" v-if="currentId ==  `launchForm-stock`">|</div>
                </div>
              </uv-form-item>
            </div>
          </div>
          <div class="bfff pl30 details pr30 mt20" style="text-align: right;">
            <uv-form-item label="产品详情" prop="details" labelPosition="top">
              <uv-upload @delete="deletePic" @afterRead="afterRead" :fileList="launchForm.details" name="details" :maxCount="6">
                <div class="p1757567255 f mt20 aic jcc">
                  <uv-icon size="100rpx" color="#C9CACA" name="camera"></uv-icon>
                </div>
              </uv-upload>
            </uv-form-item>
          </div>
        </uv-form>
      </div>
      <button-lst bgColor="" text="保存" @submit="submitTap"></button-lst>
    </div>

    <u-lst-keyboard :tooltip="false" mode="number" :dotDisabled="dotDisabled" @close="keyboardClose" @change="keyboardConfirm" ref="keyboardRef" :text="tips"></u-lst-keyboard>
    <uv-picker keyName="cate_name" ref="_cate_idPicker" :columns="cate_idList" @confirm="confirm"></uv-picker>

  </div>
</template>

<script>

import myLayOutVue from '../components/layOut.vue'

import keyboardPopupVue from '@/components/Lkeyboard.vue'
import { uploadImage, videoUpload } from '@/api'
import { category, addGoods, detailGoods, merchantProfileedit } from "@/api/merchant.js";
import pageMixin from "../mixin/page.js";
import commonButtonVue from "../components/commonButton.vue";

export default {
  components: {
    'u-my-layOut': myLayOutVue,
    "button-lst": commonButtonVue,
    'u-lst-keyboard': keyboardPopupVue,
  },
  mixins: [pageMixin],
  data() {
    return {
      dotDisabled: true,
      translateY: 0,
      translatePopupY: 0,
      currentId: '',
      cate_idList: [],
      tips: '',
      valueProp: '',
      fileList: [],
      communityForm: {},
      statusBarHeight: 0,
      name: '',
      service_status: false,
      launchForm: {
        images: [],
        video_link: [],
        details: [],
        store_name: '',
        store_info: '',
        is_postage: '1',
        _cate_id: '',
        postage: '',
        store_safeguard: '付款后3天内发货·七天无理由退货',
        _sku_object: '',
        stock: '',
        market_price: '',
        price: '',
      },
      rules: {
        'images': { type: 'array', required: true, message: '商品图片', trigger: ['blur', 'change'] },
        // 'video_link': { type: 'array', required: true, message: '商品视频', trigger: ['blur', 'change'] },
        // 'details': { type: 'array', required: true, message: '产品详情图片', trigger: ['blur', 'change'] },
        'store_name': { type: 'string', required: true, message: '请输入产品名称', trigger: ['blur', 'change'] },
        'store_info': { type: 'string', required: true, message: '请输入描述信息', trigger: ['blur', 'change'] },
        '_cate_id': { type: 'string', required: true, message: '产品分类', trigger: ['blur', 'change'] },
        'postage': { type: 'string', required: true, message: '请输入邮费', trigger: ['blur', 'change'] },
        // '_sku_object': { type: 'string', required: true, message: '请输入产品规格', trigger: ['blur', 'change'] },
        'market_price': { type: 'string', required: true, message: '请输入划线价', trigger: ['blur', 'change'] },
        'price': { type: 'string', required: true, message: '请输入售价', trigger: ['blur', 'change'] },
        'stock': [{ type: 'string', required: true, message: '请输入库存', trigger: ['blur', 'change'] }],
      },
      radio: '',
      isOnShow: false,
      routeQuery: {}

    }
  },

  onHide() {
    this.isOnShow = true
  },
  onLoad(options) {
    if (options) this.routeQuery = options
    if (this.routeQuery.id) {
      this.initPage()
    } else {
      this._initForm()
    }
  },
  onShow() {
    if (this.isOnShow) this._initForm()
    try {
      this.statusBarHeight = uni.getWindowInfo().statusBarHeight || uni.getMenuButtonBoundingClientRect().top;
    } catch (error) {
    }
    this._list()
  },
  methods: {
    initPage() {
      detailGoods(this.routeQuery.id).then(res => {
        if (res.code === 200) {
          let data = JSON.parse(JSON.stringify(res.result))
          let launchForm = {
            id: data.id,
            images: data.images.map(i => { return { url: i } }),
            video_link: !data.video_link ? [] : [{ url: data.video_link }],
            store_name: data.store_name,
            store_info: data.store_info,
            is_postage: String(data.is_postage),
            postage: this.removeTrailingZeros(data.postage) == 0 ? '' : this.removeTrailingZeros(data.postage),
            _cate_id: data.cate_name,
            cate_id: data.cate_id,
            store_safeguard: '付款后3天内发货·七天无理由退货',
            _sku_object: data.spec_type == 0 ? '' : `共${res.result.sku_object.skus.length}个规格`,
            market_price: data.spec_type == 0 ? this.removeTrailingZeros(data.market_price) : '',
            price: data.spec_type == 0 ? this.removeTrailingZeros(data.price) : '',
            stock: data.spec_type == 0 ? this.removeTrailingZeros(data.stock) : '',
            spec_type: data.spec_type
          }
          if (data.details) {
            if (Array.isArray(data.details)) {
              launchForm.details = data.details.map(i => { return { url: i } })
            } else {
              launchForm.details = data.details.split(',').map(i => { return { url: i } })
            }

          } else {
            launchForm.details = []
          }
          let specsList = []
          let strGrouped = []
          if (data.sku_object.specs && data.sku_object.specs.length) {
            specsList = data.sku_object.specs.map(item => {
              item.values = item.values
              return item
            })
          }
          if (data.sku_object.skus && data.sku_object.skus.length) {
            strGrouped = this.toMultidimensionalByRule(data.sku_object.skus, (str) => {
              return str.spec_values[0]
            });
          }
          launchForm.sku_object = {
            specs: specsList,
            _skus: this._skus(strGrouped),
            skus: data.sku_object.skus
          }
          this.launchForm = launchForm

        }
      })

    },
    removeTrailingZeros(str) {
      if (this.isEmpty(str)) {
        return ''
      }
      return String(str).replace(/(\.\d*?[1-9])0+$|\.0+$/, '$1');
    },
    _skus(data) {
      let specsList = []
      data.forEach((value, ci) => {
        value.forEach((item, index) => {
          item.id = item.id || 0
          item.name = item.spec_values.join(',')
          item.weight = this.removeTrailingZeros(item.weight) || null
          item.price = this.removeTrailingZeros(item.price) || null
          item.stock = this.removeTrailingZeros(item.stock) || null
          item.market_price = this.removeTrailingZeros(item.market_price) || null
          item._image = item.image
          if (Array.isArray(item.image)) {
            item._image = item.image
          } else {
            item._image = item.image && [{ url: item.image }] || []
          }
        })
        specsList.push({ name: value[0].spec_values[0], values: value })
      })
      return specsList
    },
    toMultidimensionalByRule(arr, rule) {
      if (!Array.isArray(arr) || typeof rule !== 'function') {
        return [];
      }

      const groupMap = {};
      // 按规则函数返回的标识分组
      arr.forEach(item => {
        const key = rule(item); // 执行规则函数获取分组标识
        if (!groupMap[key]) {
          groupMap[key] = [];
        }
        groupMap[key].push(item);
      });

      // 将对象值转换为数组
      return Object.values(groupMap);
    },
    _initForm() {
      uni.getStorage({
        key: 'storageForm', success: res => {
          if (res.data) {
            this.launchForm = JSON.parse(res.data)
          }
        }
      });
    },
    _list() {
      category().then(res => {
        if (res.code == 200) {
          this.cate_idList = [res.result]
        }
      }).catch(errors => {
      })
    },
    openTap(prop) {
      this.valueProp = prop
      this.$refs[prop + 'Picker'].open();
    },
    confirm(e) {
      let newProp = this.valueProp.substring(1, this.valueProp.length)
      this.$set(this.launchForm, this.valueProp, e.value[0].cate_name)
      this.$set(this.launchForm, newProp, e.value[0].id)
    },
    setNumber(prop) {
      this.tips = this.launchForm[prop]
      this.valueProp = prop
      this.$nextTick(() => {
        this.$refs.keyboard.open()
      })
    },
    keyboardConfirm(value) {
      let str = this.launchForm[this.valueProp]
      this.$set(this.launchForm, this.valueProp, value && String(value))
      this.$refs.form.validateField(this.valueProp)
    },
    openKeyboardTap(prop) {
      this.currentId = 'launchForm-' + prop
      this.valueProp = prop
      this.tips = this.launchForm[prop]
      this.$nextTick(() => {
        this.$refs.keyboardRef.open((keyboardHeight, keyboardTop) => {
          if (this.keyboardHeight == 0) this.keyboardHeight = keyboardHeight
          if (this.keyboardTop == 0) this.keyboardTop = keyboardTop
          uni.createSelectorQuery().in(this).select('#' + this.currentId).boundingClientRect(data => {
            if ((keyboardTop - keyboardHeight) < (data.top + data.height)) {
              this.translateY = -(((data.top + data.height) - (keyboardTop - keyboardHeight)) + this.safeAreaInsetsBottom + 10)
            }
          }).exec();
        })
      })
    },
    navigateToTap() {
      uni.setStorage({ key: 'storageForm', data: JSON.stringify(this.launchForm) });
      uni.navigateTo({
        url: '/pages-merchant/product/specifications'
      });
    },
    submitTap() {
      this.$refs.form.validate().then(res => {
        let launchForm = JSON.parse(JSON.stringify(this.launchForm))
        let specs = []
        launchForm.images = launchForm.images.map(item => {
          return item.url
        })

        // if (launchForm.sku_object && launchForm.sku_object.specs?.length) {
        //   specs = launchForm.sku_object.specs.map(item => {
        //     return item.url
        //   })
        // }

        if (launchForm.is_postage == 1) {
          delete launchForm.postage
        }
        if (launchForm.details.length) {
          launchForm.details = launchForm.details.map(item => {
            return item.url
          })
        } else {
          delete launchForm.details
        }
        if (launchForm.video_link.length) {
          launchForm.video_link = launchForm.video_link[0].url
        } else {
          delete launchForm.video_link
        }
        if (launchForm._sku_object) {
          delete launchForm.price
          delete launchForm.market_price
          delete launchForm.stock
        }
        if (launchForm.sku_object._skus) {
          delete launchForm.sku_object._skus
        }
        delete launchForm._cate_id
        delete launchForm._sku_object
        delete launchForm.cate_idPicker
        uni.showLoading({ title: '请求中', mask: true })

        if (this.launchForm.id) {
          merchantProfileedit(launchForm).then(res => {
            if (res.code === 200) {
              uni.removeStorage({ key: 'storageForm' });
              uni.$uv.toast('操作成功')
              setTimeout(() => {
                uni.hideLoading()
                uni.navigateBack({ delta: 1 });
              }, 1000)
            }
          })
        } else {
          addGoods(launchForm).then(res => {
            if (res.code === 200) {
              uni.removeStorage({ key: 'storageForm' });
              uni.$uv.toast('操作成功')
              setTimeout(() => {
                uni.hideLoading()
                uni.navigateBack({ delta: 1 });
              }, 1000)
            }
          })
        }
      })

    },
    keyboardClose() {
      this.translateY = 0
      this.translatePopupY = 0
      this.currentId = ''
      this.tips = ''
    },
    afterRead(file) {
      uni.showLoading({ title: '上传中', mask: true })
      if (file.name == 'video_link') {
        videoUpload({ name: 'file', filePath: file.file.url }).then(res => {
          uni.hideLoading()
          if (res.code === 0) {
            this.$set(this.launchForm, file.name, [{ url: res.data.url }])
          }
        })
      } else {
        uploadImage({ name: 'file', filePath: file.file.thumb }).then(res => {
          uni.hideLoading()
          if (res.code === 0) {
            if (file.name == 'images' || file.name == 'details') {
              this.$set(this.launchForm, file.name, this.launchForm[file.name].concat([{ url: res.data }]))
            } else {
              this.$set(this.launchForm, file.name, [{ url: res.data }])
            }
          }
        })
      }

    },
    deletePic(file) {
      if (file.name == 'images' || file.name == 'details') {
        this.launchForm[file.name].splice(file.index, 1)
      } else {
        this.$set(this.launchForm, file.name, [])
      }
    },

  }
}
</script>
<style>
page {
  background-color: #f7f8f8;
  color: #333;
}
</style>
<style lang="scss" scoped>
@import "../common.scss";
.p1757567255 {
  width: calc(33.3333vw - 34rpx) !important;
  min-width: calc(33.3333vw - 34rpx) !important;
  max-width: calc(33.3333vw - 34rpx) !important;
  height: 130rpx !important;
  background: #f6f4f7;
  border-radius: 8rpx;
}
.p1757555505 {
  display: flex;
  width: 100%;
  justify-content: flex-end;
}
.p1757569449 {
  height: 90rpx;
  background: #de0012 !important;
  font-weight: 500;
  font-size: 36rpx !important;
  color: #ffffff !important;
  border-radius: 8rpx !important;
  width: 100%;
}
.p1757903903 {
  display: inline-block;
  font-size: 30rpx;
  overflow-x: auto;
  white-space: nowrap;
  width: 100%;
}
</style>

